﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using NetWork.Sockets.Event.Msg;
using NetWork.Packets;

namespace NetWork.Sockets.Event
{
    public class EventManger
    {
        private Dictionary<int, DelegateFunc> msgHandle = new Dictionary<int, DelegateFunc>();
        //private Dictionary<int, Dictionary<int, MsgPacket>> msgHandle = new Dictionary<int, Dictionary<int, MsgPacket>>();
        private Queue<Packet> packets = new Queue<Packet>();

        public void RegisterMsgListener(int nMsgId, DelegateFunc handler)
        {
            if (!msgHandle.ContainsKey(nMsgId))
            {
                msgHandle[nMsgId] = handler;
            }
            else
            {
                msgHandle[nMsgId] += handler;
            }
        }

        public void UnRegistMsgListener(int nMsgId, DelegateFunc handler)
        {
            if (msgHandle.ContainsKey(nMsgId))
            {
                msgHandle[nMsgId] -= handler;
            }
            else
            {
                Debug.LogError("[EventManager] Opcode:" + nMsgId + " not have Regist Handler But call UnRegist");
            }
        }

        public void AddPacket(Packet kPacket)
        {
            packets.Enqueue(kPacket);
        }

        public void Tick()
        {
            while (packets.Count > 0)
            {
                Packet temp = packets.Dequeue();

                if(temp.nOpCode == ProtoBuf.Message.OpDefine.ErrorMessage)
                {
                    var err =  (ProtoBuf.Message.ErrorMessage)temp.kBody;
                    string errMsg = "" + err.msg+"";
                    
                    if(int.Parse(err.code)==21)
                    {
                        BoxManager.CreateReloginBox(err.msg);
                        break;
                    }

                    if(int.Parse(err.code)== 812)//特殊处理，对方处于组队情况
                    {
                        BoxManager.CreatePopupTextBox(errMsg,0.8f);
                    }
                    else
                    {
                        BoxManager.CreatePopupTextBox(errMsg);
                    }
                }

#if UNITY_EDITOR
                //Debug.Log("socket receive packet "+temp.nOpCode);
#endif
                if (msgHandle.ContainsKey(temp.nOpCode))
                {
                    if(msgHandle[temp.nOpCode] != null)
                    {
                        msgHandle[temp.nOpCode](temp.kBody);
                    }
                    else
                    {
                        Debug.LogWarning("socket message " + temp.nOpCode + " not has handler");
                    }
                }

            }
        }
    }
}